package com.keyinong.caizhengting.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.MyFragmentReplace;
import com.keyinong.caizhengting.fragment.ErweimaFragment;
import com.keyinong.caizhengting.fragment.MyFragment;
import com.keyinong.caizhengting.fragment.MyorderFragment;
import com.keyinong.caizhengting.fragment.ShoppingCartsFragment;
import com.keyinong.caizhengting.fragment.ShouyeFragment;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author：郑谦
 * @时间：2017-3-10 下午4:02:27
 * @类名：FanqiedingcanActivity.java
 * @功能: 主界面
 */

public class FanqiedingcanActivity extends FragmentActivity {

    /**
     * 购物车
     */
    private static RadioButton rb_gouwuche;
    /** frame */
//	private FrameLayout fram_jishibao;
    /**
     * 二维码
     */
    private static RadioButton rb_erweima;
    /**
     * 我的订单
     */
    private static RadioButton rb_wodedingdan;
    /**
     * 隐藏商品详情按钮
     */
    private static RadioButton rb_detail;
    /**
     * 购物车数量
     */
    private static TextView tv_number;
    public static Handler myhanler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            Bundle bu = (Bundle) msg.obj;
            String sopt1 = bu.getString("sopt1");
            String str1 = bu.getString("str1");
            int index1 = bu.getInt("index1");
            if (sopt1.equals("jia1")) {
                tv_number.setVisibility(View.VISIBLE);
                tv_number.setText(str1 + "");
                //				Log.i("shi", "str="+infolist.get(index).getAmount());
            }
            if (sopt1.equals("jian1")) {
                tv_number.setVisibility(View.VISIBLE);
                tv_number.setText(str1 + "");
            }

            if (sopt1.equals("qingchu1")) {
                if (str1.equals("0")) {
                    tv_number.setVisibility(View.GONE);
                } else {
                    tv_number.setVisibility(View.VISIBLE);
                    tv_number.setText(str1 + "");
                }

            }
            super.handleMessage(msg);
        }

    };
    public static Handler myhanler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            Bundle bu = (Bundle) msg.obj;
            String sopt = bu.getString("sopt");
            String str = bu.getString("str");
            int index = bu.getInt("index");
            if (sopt.equals("jia")) {
                tv_number.setVisibility(View.VISIBLE);
                tv_number.setText(str + "");
                //				Log.i("shi", "str="+infolist.get(index).getAmount());
            }
            if (sopt.equals("jian")) {
                tv_number.setVisibility(View.VISIBLE);
                tv_number.setText(str + "");
            }

            if (sopt.equals("qingchu")) {
                if (str.equals("0")) {
                    tv_number.setVisibility(View.GONE);
                } else {
                    tv_number.setVisibility(View.VISIBLE);
                    tv_number.setText(str + "");
                }

            }
            super.handleMessage(msg);
        }

    };
    private static int IS_CURRENT_PAGE = 1;
    public static Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
//				rb_meeting.performClick();
                    break;
                case 2:
//				rb_add.performClick();
                    break;
                case 3:
                    IS_CURRENT_PAGE = 3;
                    //            	 sercolor(rb_meeting, rb_home, rb_commute, rb_My);
//				rb_Search.setChecked(true);
                    rb_erweima.performClick();
                    break;
                default:
                    break;
            }
        }

    };
    View iscatview = null;
    long time;
    HttpTools httpTools = null;
    /**
     * 首页
     */
    private RadioButton rb_shouye;
    /**
     * 个人中心
     */
    private RadioButton rb_my;
    private String token;
    private String productid;
    private OnClickListener rbOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                // 首页
                case R.id.rb_shouye:
                    if (IS_CURRENT_PAGE != 1) {
                        ShouyeFragment home = new ShouyeFragment();
                        MyFragmentReplace.fragmentReplace(FanqiedingcanActivity.this,
                                R.id.fram_fanqiedingcan, home);
                        IS_CURRENT_PAGE = 1;
//					startActivityForResult(intent, requestCode)
                    }
                    break;
                // 购物车
                case R.id.rb_gouwuche:
                    if (IS_CURRENT_PAGE != 2) {
                        ShoppingCartsFragment oftenbuy = new ShoppingCartsFragment();
                        MyFragmentReplace.fragmentReplace(FanqiedingcanActivity.this,
                                R.id.fram_fanqiedingcan, oftenbuy);

//					int count=oftenbuy.getCount();
//					Log.i("lh", "count---"+count);
//					if (count > 0) {
//						tv_number.setText(String.valueOf(count));
//						tv_number.setVisibility(View.VISIBLE);
//					} else {
//						tv_number.setVisibility(View.INVISIBLE);
//					}
                        IS_CURRENT_PAGE = 2;

                    }
                    break;
                // 二维码
                case R.id.rb_erweima:
                    if (IS_CURRENT_PAGE != 3) {
                        ErweimaFragment erweima = new ErweimaFragment();
                        MyFragmentReplace.fragmentReplace(FanqiedingcanActivity.this,
                                R.id.fram_fanqiedingcan, erweima);
                        IS_CURRENT_PAGE = 3;
                    }
                    break;
                // 我的订单
                case R.id.rb_wodedingdan:
                    if (IS_CURRENT_PAGE != 4) {
                        MyorderFragment order = new MyorderFragment();
                        MyFragmentReplace.fragmentReplace(FanqiedingcanActivity.this,
                                R.id.fram_fanqiedingcan, order);
                        IS_CURRENT_PAGE = 4;
                    }
                    break;
                // 个人中心
                case R.id.rb_my:
                    if (IS_CURRENT_PAGE != 5) {
                        MyFragment my = new MyFragment();
                        MyFragmentReplace.fragmentReplace(FanqiedingcanActivity.this,
                                R.id.fram_fanqiedingcan, my);
                        IS_CURRENT_PAGE = 5;
                    }
                    break;
                // 商品详情
                case R.id.rb_detail:
                    if (IS_CURRENT_PAGE != 6) {
                        IS_CURRENT_PAGE = 6;
                        MyFragment detail = new MyFragment();
//					MyFragmentReplace.fragmentReplace(FanqiedingcanActivity.this,
//							R.id.fram_fanqiedingcan, my);
                        Bundle bundle = new Bundle();
                        bundle.putString("productid", productid);
                        replceFragment(detail, bundle);
                        productid = "";
                    }
                    break;

                default:
                    break;
            }

        }
    };
    private long exitTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_fanqiedingcan);
        initRes();
        //友盟推送服务
        UmengPush();
    }

    private void initRes() {
//		fram_jishibao = (FrameLayout) findViewById(R.id.fram_jishibao);
        rb_shouye = (RadioButton) findViewById(R.id.rb_shouye);
        rb_gouwuche = (RadioButton) findViewById(R.id.rb_gouwuche);
        rb_erweima = (RadioButton) findViewById(R.id.rb_erweima);
        rb_wodedingdan = (RadioButton) findViewById(R.id.rb_wodedingdan);
        rb_my = (RadioButton) findViewById(R.id.rb_my);
        rb_detail = (RadioButton) findViewById(R.id.rb_detail);
        tv_number = (TextView) findViewById(R.id.tv_number);

        String code = getIntent().getStringExtra("code");
        if (code != null && code.equals("1")) {
            ShoppingCartsFragment gouwuche = new ShoppingCartsFragment();
            MyFragmentReplace.fragmentReplace(FanqiedingcanActivity.this,
                    R.id.fram_fanqiedingcan, gouwuche);
            rb_gouwuche.performClick();
            IS_CURRENT_PAGE = 2;
//			rb_gouwuche.setChecked(true);
        } else if (code != null && code.equals("2")) {
            MyorderFragment order = new MyorderFragment();
            MyFragmentReplace.fragmentReplace(FanqiedingcanActivity.this,
                    R.id.fram_fanqiedingcan, order);
            rb_wodedingdan.performClick();
            IS_CURRENT_PAGE = 4;
        } else {
            ShouyeFragment home = new ShouyeFragment();
            MyFragmentReplace.fragmentReplace(FanqiedingcanActivity.this,
                    R.id.fram_fanqiedingcan, home);
        }

//		classintent();
        myShoppingCat();
        try {
            getVersionName();
//			Log.e("zq", "getVersionName()-----"+getVersionName());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        getVersions();
        setRbOnClick();
    }

    private void setRbOnClick() {
        rb_shouye.setOnClickListener(rbOnClickListener);
        rb_gouwuche.setOnClickListener(rbOnClickListener);
        rb_erweima.setOnClickListener(rbOnClickListener);
        rb_wodedingdan.setOnClickListener(rbOnClickListener);
        rb_my.setOnClickListener(rbOnClickListener);
        rb_detail.setOnClickListener(rbOnClickListener);
    }

    /**
     * 友盟推送开发服务
     */
    private void UmengPush() {
        //开启推送服务
        PushAgent mPushAgent = PushAgent.getInstance(FanqiedingcanActivity.this);
        mPushAgent.enable();
        //开启回掉处理
        //获取设备的device_token（可选）
        String device_token = UmengRegistrar.getRegistrationId(FanqiedingcanActivity.this);
        Log.e("zq", device_token);
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        Log.e("lh", token);
        //		 feb14cd64351104f8ac2d4ed31259630

        //统计应用启动数据
//		Log.e("zq", "**************");
        PushAgent.getInstance(FanqiedingcanActivity.this).onAppStart();
        //try {
        //	//mPushAgent.addAlias(token, ALIAS_TYPE.BAIDU);
        //} catch (e e) {
        //	e.printStackTrace();
        //} catch (JSONException e) {
        //	e.printStackTrace();
        //} catch (Exception e) {
        //	e.printStackTrace();
        //}
    }

    /**
     * 获取购物车商品数量设置角标
     */
    private void myShoppingCat() {
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        token = sp.getString("data", "");
//		Log.i("zq", "token--"+token);
//		TTs();
        if (httpTools == null) {
            httpTools = new HttpTools(FanqiedingcanActivity.this);
        }
        httpTools.getShoppingCat(token, new JsonShoppingCat());
    }

    /**
     * 获取当前版本号
     */
    private void getVersions() {
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        token = sp.getString("data", "");
        if (httpTools == null) {
            httpTools = new HttpTools(FanqiedingcanActivity.this);
        }
        httpTools.getVersion(token, new JsonGetversions());
    }

    /**
     * 新版本更新提示弹窗
     */
    private void versiondialog() {

        final Dialog dialog = new Dialog(FanqiedingcanActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        iscatview = LayoutInflater.from(FanqiedingcanActivity.this).inflate(
                R.layout.dialog_pay, null);
        TextView tital = (TextView) iscatview.findViewById(R.id.tital);
        TextView tv_no = (TextView) iscatview.findViewById(R.id.tv_no);
        TextView tv_yes = (TextView) iscatview.findViewById(R.id.tv_yes);
        tital.setText("发现新版本，是否立即更新？");
        dialog.setContentView(iscatview);
        dialog.show();
        tv_no.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tv_yes.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(FanqiedingcanActivity.this, VersionActivity.class);
                startActivity(intent);
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        /**开启线程用于监听log输出的信息**/
//		handler.postDelayed(runnable, 1000);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
//		handler.removeCallbacks(runnable);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 切换Fragment
     */
    private void replceFragment(Fragment fragment) {
        FragmentManager fManager = getSupportFragmentManager();
        FragmentTransaction fTransaction = fManager.beginTransaction();
        fTransaction.replace(R.id.fram_fanqiedingcan, fragment);
        fTransaction.commit();
    }

    private void replceFragment(Fragment fragment, Bundle bundle) {
        FragmentManager fManager = getSupportFragmentManager();
        FragmentTransaction fTransaction = fManager.beginTransaction();
        fragment.setArguments(bundle);
        fTransaction.replace(R.id.fram_fanqiedingcan, fragment);
        fTransaction.commit();
    }

    private String getVersionName() {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String version = packInfo.versionName;
        return version;
    }

    private class JsonShoppingCat extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            super.onSuccess(statusCode, headers, response);
//			Log.e("zq", "shopcat---" + response.toString());
            try {
                boolean code = response.getBoolean("code");
                if (code == true) {
                    JSONObject object = response.getJSONObject("data");
//					String isnew = object.getString("isnew");
//					JSONArray array = object.getJSONArray("orders");
                    String amount = object.getString("amount");
//					Log.i("zq", "array---"+array.length());
                    if (amount.equals("0")) {
                        tv_number.setVisibility(View.GONE);
                    } else {
                        tv_number.setVisibility(View.VISIBLE);
                        tv_number.setText("" + amount);
                    }
                } else {
//					String msg = response.getString("msg");
//					Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    private class JsonGetversions extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            super.onSuccess(statusCode, headers, response);
//			Log.e("zq", "shopcat---" + response.toString());
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    JSONObject object = response.getJSONObject("data");
                    String version = object.getString("version");
                    if (!version.equals(getVersionName())) {
                        versiondialog();
                    }
                } else {
//					String msg = response.getString("msg");
//					Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

//	ShouyeFragment shouyeFragment;
//	GouwucheFragment gouwucheFragment;
//	WodedingdanFragment wodedingdanFragment;
//	MyFragment myFragment;
//	RadioButton[] rbArray = new RadioButton[4];
//
//	Fragment[] fragmentArray = null;
//	/**
//	 * 当前显示的fragment
//	 */
//	int currentIndex = 0;
//	/**
//	 * 选中的button,显示下一个fragment
//	 */
//	int selectedIndex;
//
//	@Override
//	protected void onCreate(Bundle arg0) {
//		// TODO Auto-generated method stub
//		super.onCreate(arg0);
//		try {
//			setContentView(R.layout.activity_fanqiedingcan);
//			setupView();
//			addListener();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
//
//	private void addListener() {
//		MyButtonListener myButtonListener = new MyButtonListener();
//		for (int i = 0; i < rbArray.length; i++) {
//			rbArray[i].setOnClickListener(myButtonListener);
//		}
//	}
//
//	private void setupView() {
//		rbArray[0] = (RadioButton) findViewById(R.id.rb_shouye);
//		rbArray[1] = (RadioButton) findViewById(R.id.rb_gouwucheng);
//		rbArray[2] = (RadioButton) findViewById(R.id.rb_wodedingdan);
//		rbArray[3] = (RadioButton) findViewById(R.id.rb_my);
//		rbArray[0].setSelected(true);
//
//		shouyeFragment = new ShouyeFragment();
//		gouwucheFragment = new GouwucheFragment();
//		wodedingdanFragment = new WodedingdanFragment();
//		myFragment = new MyFragment();
//		fragmentArray = new Fragment[] { shouyeFragment, gouwucheFragment,
//				wodedingdanFragment, myFragment };
//
//		// 一开始，显示第一个fragment
//		FragmentManager fragmentManager = getSupportFragmentManager();
//		FragmentTransaction transaction = fragmentManager.beginTransaction();
//		transaction.add(R.id.fram_fanqiedingcan, shouyeFragment);
//		transaction.show(shouyeFragment);
//		transaction.commit();
//
//	}
//
//	class MyButtonListener implements OnClickListener {
//
//		@Override
//		public void onClick(View v) {
//			try {
//				switch (v.getId()) {
//				case R.id.rb_shouye:
//					selectedIndex = 0;
//					break;
//				case R.id.rb_gouwucheng:
//					selectedIndex = 1;
//					break;
//				case R.id.rb_wodedingdan:
//					selectedIndex = 2;
//					break;
//				case R.id.rb_my:
//					selectedIndex = 3;
//					break;
//				}
//
//				// 判断单击是不是当前的
//				if (selectedIndex != currentIndex) {
//					// 不是当前的
//					FragmentTransaction transaction = getSupportFragmentManager()
//							.beginTransaction();
//					// 当前hide
//					transaction.hide(fragmentArray[currentIndex]);
//					// show你选中
//
//					if (!fragmentArray[selectedIndex].isAdded()) {
//						// 以前没添加过
//						transaction.add(R.id.fram_fanqiedingcan,
//								fragmentArray[selectedIndex]);
//					}
//					// 事务
//					transaction.show(fragmentArray[selectedIndex]);
//					transaction.commit();
//
//					rbArray[currentIndex].setSelected(false);
//					rbArray[selectedIndex].setSelected(true);
//					currentIndex = selectedIndex;
//
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//
//		}
//
//	}
}